package com.yff.tuan.util;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yff.tuan.model.VehicleCheck;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;  
  
public class AppSendUtils {  
    private static final String apk = "eFwaDGcAsgWzRhGYxi2MuWhr3GV4Pmm4";
    private static Logger logger = LoggerFactory.getLogger(AppSendUtils.class);
    public static VehicleCheck getBaiduMap(VehicleCheck vehicleCheck) {
    	if(null != vehicleCheck && StringUtils.isNotEmpty(vehicleCheck.getLat()) && StringUtils.isNotEmpty(vehicleCheck.getLng())){
    		String lat = vehicleCheck.getLat().trim();
    		String lng = vehicleCheck.getLng().trim();
    		String coords = lng+","+lat;
    		String requestUrl = "http://api.map.baidu.com/geoconv/v1/?coords="+coords+"&from=1&to=5&output=json&ak="+apk;
            CloseableHttpClient httpclient = HttpClients.createDefault();
    		CloseableHttpResponse resp = null;
    		try {
				HttpGet httpGet = new HttpGet(requestUrl);
				resp = httpclient.execute(httpGet);
				String responseBody = EntityUtils.toString(resp.getEntity(),Charset.forName("utf-8"));
    			JSONObject object = JSONObject.fromObject(responseBody);
    			if(object.containsKey("result")){
    				JSONArray array = JSONArray.fromObject(object.get("result"));
    				JSONObject  position = (JSONObject) array.get(0);
    				vehicleCheck.setLat(""+position.get("y"));
    				vehicleCheck.setLng(""+position.get("x"));
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally {
    			try {
    				resp.close();
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
    	}
    	logger.info(vehicleCheck.toString());
        return vehicleCheck;  
    }  
  
    public static void main(String[] args) {   	
    	VehicleCheck vehicleCheck = new VehicleCheck();
    	vehicleCheck.setLat("26.0870030 ");
    	vehicleCheck.setLng("119.3506897 ");
    	vehicleCheck = getBaiduMap(vehicleCheck);  
    	System.out.println(vehicleCheck.getLat());
    	System.out.println(vehicleCheck.getLng());
    	//{"status":0,"result":[{"x":119.36216245425983,"y":26.089752937462074}]}
    }  
}  